/**
 * 数据类型检测工具
 * 用于检测testDetail JSON数据对应的Java类类型
 */

// 数据类型检测规则
const detectionRules = [
  {
    type: 'screw',
    name: '螺丝拧紧类型',
    patterns: [
      'screwCCDcheckResult',
      'screwCCDResult',
      'tightenResult01',
      'tightenResult02',
      'tightenResult03',
      'tightenResult04',
      'programNo01',
      'minTorque01',
      'actTorque01',
      'maxTorque01',
      'minAngle01',
      'screwBatchNo',
      'screwBtachNo',
      'sealingRing'
    ],
    javaClasses: [
      'OP01Data',
      'OP07Data',
      'OP09Data',
      'OP11Data',
      'OP21Data',
      'OP23Data'
    ]
  },
  {
    type: 'resistance',
    name: '电阻测试类型',
    patterns: [
      'testResistanceResult01',
      'testResistanceResult02',
      'testResistanceResult03',
      'testDielectricResult',
      'testHeightVoltageResult',
      'testProgramNo',
      'testResistance01',
      'testResistanceMax01',
      'testDielectric',
      'testHeightVoltage'
    ],
    javaClasses: [
      'OP25_1Data',
      'OP25_2Data'
    ]
  },
  {
    type: 'load',
    name: '上料类型',
    patterns: [
      'partLoadResult',
      'partCCDCheckResult',
      'partPlaceInResult',
      'housingMaterialNo',
      'controllerMaterialNo',
      'phaseMaterialNo',
      'wireMaterialNo',
      'busbarMaterialNo',
      'thinFilmCapacitorMaterialNo',
      'filterCapacitorMaterialNo'
    ],
    javaClasses: [
      'OP02_1DataFirst',
      'OP05Data',
      'OP16Data'
    ]
  },
  {
    type: 'glue',
    name: '涂胶类型',
    patterns: [
      'glueHousingResult',
      'glueControllerResult',
      'gluePhaseResult',
      'glueWireResult',
      'glueBusbarResult',
      'housingGlueResult',
      'glueCCDResult',
      'glueCCDResult01',
      'glueCCDResult02',
      'glueCCDResult03',
      'glueCCDResult04',
      'glueCCDResult05',
      'glueBatchNo'
    ],
    javaClasses: [
      'OP03Data',
      'OP04Data',
      'OP15Data'
    ]
  },
  {
    type: 'clean',
    name: '清洗类型',
    patterns: [
      'housingPlasmaResult',
      'controllerPlasmaResult',
      'phasePlasmaResult',
      'wirePlasmaResult',
      'busbarPlasmaResult',
      'tesFillPressureResult',
      'testLeakageResult'
    ],
    javaClasses: [
      'OP02_2Data',
      'OP14Data'
    ]
  },
  {
    type: 'camera',
    name: '相机检测类型',
    patterns: [
      'cameraResult01',
      'cameraResult02',
      'cameraResult03',
      'oringCCDResult',
      'partCCDResult1',
      'partCCDResult01',
      'partCCDResult02',
      'partCCDResult03',
      'partCCDResult04',
      'partCCDResult05',
      'partCCDResult06',
      'partCCDResult07',
      'partCCDResult08',
      'partCCDResult09',
      'partCCDResult10',
      'partCCDResult11',
      'partCCDResult12'
    ],
    javaClasses: [
      'OP27DataFirst',
      'OP27Data'
    ]
  }
]

/**
 * 检测数据类型
 * @param {object} data 要检测的数据对象
 * @returns {string} 检测到的数据类型
 */
export function detectDataType(data) {
  if (!data || typeof data !== 'object') {
    return 'default'
  }

  const dataKeys = Object.keys(data)
  let bestMatch = { type: 'default', score: 0 }

  // 遍历所有检测规则
  for (const rule of detectionRules) {
    let matchCount = 0

    // 计算匹配的字段数量
    for (const pattern of rule.patterns) {
      if (dataKeys.includes(pattern)) {
        matchCount++
      }
    }

    // 计算匹配分数（匹配字段数 / 总字段数）
    const score = matchCount / rule.patterns.length

    // 如果匹配分数更高，更新最佳匹配
    if (score > bestMatch.score && matchCount > 0) {
      bestMatch = { type: rule.type, score, matchCount, rule }
    }
  }

  // 如果最佳匹配分数太低，返回默认类型
  if (bestMatch.score < 0.1) {
    return 'default'
  }

  return bestMatch.type
}

/**
 * 获取数据类型的详细信息
 * @param {object} data 要检测的数据对象
 * @returns {object} 检测结果详情
 */
export function getDataTypeInfo(data) {
  if (!data || typeof data !== 'object') {
    return {
      type: 'default',
      name: '默认类型',
      score: 0,
      matchedFields: [],
      possibleClasses: []
    }
  }

  const dataKeys = Object.keys(data)
  let bestMatch = {
    type: 'default',
    name: '默认类型',
    score: 0,
    matchedFields: [],
    possibleClasses: []
  }

  // 遍历所有检测规则
  for (const rule of detectionRules) {
    const matchedFields = []

    // 找出匹配的字段
    for (const pattern of rule.patterns) {
      if (dataKeys.includes(pattern)) {
        matchedFields.push(pattern)
      }
    }

    // 计算匹配分数
    const score = matchedFields.length / rule.patterns.length

    // 如果匹配分数更高，更新最佳匹配
    if (score > bestMatch.score && matchedFields.length > 0) {
      bestMatch = {
        type: rule.type,
        name: rule.name,
        score,
        matchedFields,
        possibleClasses: rule.javaClasses
      }
    }
  }

  return bestMatch
}

/**
 * 获取所有支持的数据类型
 * @returns {array} 数据类型列表
 */
export function getSupportedDataTypes() {
  return detectionRules.map(rule => ({
    type: rule.type,
    name: rule.name,
    patterns: rule.patterns,
    javaClasses: rule.javaClasses
  }))
}

/**
 * 检查数据是否包含_1扩展类的特征
 * @param {object} data 要检测的数据对象
 * @returns {boolean} 是否为_1扩展类
 */
export function isExtensionClass(data) {
  if (!data || typeof data !== 'object') {
    return false
  }

  // 检查是否有_1扩展类的特征字段
  // 这些字段通常在_1扩展类中出现
  const extensionPatterns = [
    'testResistanceResult01', // OP25_1Data特有
    'partLoadResult', // OP02_1DataFirst特有
    'testResistanceResult02', // OP25_2Data特有
    'housingPlasmaResult' // OP02_2Data特有
  ]

  const dataKeys = Object.keys(data)
  return extensionPatterns.some(pattern => dataKeys.includes(pattern))
}

/**
 * 根据数据推测可能的Java类名
 * @param {object} data 要检测的数据对象
 * @returns {array} 可能的Java类名列表
 */
export function getPossibleJavaClasses(data) {
  const typeInfo = getDataTypeInfo(data)

  if (typeInfo.type === 'default') {
    return ['未知类型']
  }

  let classes = [...typeInfo.possibleClasses]

  // 如果是扩展类，添加_1后缀的可能性
  if (isExtensionClass(data)) {
    const extensionClasses = classes.map(cls => {
      if (!cls.includes('_')) {
        return cls + '_1'
      }
      return cls
    })
    classes = [...classes, ...extensionClasses]
  }

  return [...new Set(classes)] // 去重
}
